package com.example.administrator.recorddemo20181101;

import android.Manifest;
import android.animation.Animator;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.recorddemo20181101.adapter.FolderAdapter;
import com.example.administrator.recorddemo20181101.bean.FolderBean;
import com.example.administrator.recorddemo20181101.util.AnimUtil;
import com.example.administrator.recorddemo20181101.util.AppNetworkMgr;
import com.example.administrator.recorddemo20181101.util.AuditRecorderConfiguration;
import com.example.administrator.recorddemo20181101.util.CommomDialog;
import com.example.administrator.recorddemo20181101.util.CopyUtils;
import com.example.administrator.recorddemo20181101.util.ExtAudioRecorder;
import com.example.administrator.recorddemo20181101.util.FileUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import cn.andy.qpopuwindow.QPopuWindow;

public class FolderActivity extends AppCompatActivity {
    private TextView iv_add_folder;//添加文件夹
    /**
     * 需要申请的运行时权限
     */
    private String[] permissions = new String[]{
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    /**
     * 被用户拒绝的权限列表
     */
    private List<String> mPermissionList = new ArrayList<>();
    private FolderAdapter adapter;
    private List<FolderBean> filePath = new ArrayList<>();
    private GridView grid_view;
    private PopupWindow mPopupWindow;
    private TextView tv_name;//重命名
    private TextView tv_delete;//删除
    private static final long DURATION = 500;
    private static final float START_ALPHA = 0.7f;
    private static final float END_ALPHA = 1f;
    private AnimUtil animUtil;
    private float bgAlpha = 1f;
    private boolean bright = false;
    private String edit;
    private File[] subFile;
    private int rawX;
    private int rawY;
    private boolean isEdit = false;// 是否为编辑模式

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1001) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    Log.e("", permissions[i] + " 权限被用户禁止！");

                }
            }

        }
    }

    /**
     * 运行权限
     */
    private void checkPermissions() {
        // Marshmallow开始才用申请运行时权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (int i = 0; i < permissions.length; i++) {
                if (ContextCompat.checkSelfPermission(this, permissions[i]) !=
                        PackageManager.PERMISSION_GRANTED) {
                    mPermissionList.add(permissions[i]);
                }
            }
            if (!mPermissionList.isEmpty()) {
                String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);
                ActivityCompat.requestPermissions(this, permissions, 1001);
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_folder);
        initView();
        initData();
        initListener();
    }

    private void initView() {
        //获取权限
        checkPermissions();
        mPopupWindow = new PopupWindow(this);
        animUtil = new AnimUtil();
        //添加文件夹
        iv_add_folder = findViewById(R.id.iv_add_folder);

        grid_view = findViewById(R.id.grid_view);
    }

    private void initData() {
        //创建文件夹
        File file = new File(Environment.getExternalStorageDirectory() + "/果乐录音/");
        //判断文件夹是否存在，如果不存在就创建，否则不创建
        if (!file.exists()) {
            //通过file的mkdirs()方法创建目录中包含却不存在的文件夹
            file.mkdirs();
            Toast.makeText(FolderActivity.this, "创建成功", Toast.LENGTH_SHORT).show();
        }
        getFileName(Environment.getExternalStorageDirectory() + "/果乐录音/");
        adapter = new FolderAdapter(this, filePath);
        grid_view.setAdapter(adapter);
        //刷新 添加文件夹得到刷新
        adapter.notifyDataSetChanged();
    }


    private void initListener() {
        //点击事件
        grid_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                isEdit = false;
                Intent it = new Intent(FolderActivity.this, MainActivity.class);
                it.putExtra("path", Environment.getExternalStorageDirectory() + "/果乐录音/" + subFile[position].getName() + "/");
                startActivity(it);
            }
        });
        //添加文件夹
        iv_add_folder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAddFolderDialog();
            }
        });
        //长按事件
        grid_view.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                isEdit = true;
                QPopuWindow.getInstance(FolderActivity.this).builder
                        .bindView(view, position)
                        .setPopupItemList(new String[]{"重命名", "删除"})
                        .setPointers(rawX, rawY)
                        .setOnPopuListItemClickListener(new QPopuWindow.OnPopuListItemClickListener() {
                            @Override
                            public void onPopuListItemClick(View anchorView, final int anchorViewPosition, final int position) {
                                switch (position) {//anchorViewPosition  条数
                                    case 0://重命名
                                        Log.e("每次点击需要的文件夹名字", subFile[anchorViewPosition].getName());
                                        showRename(subFile[anchorViewPosition].getName(), anchorViewPosition);
                                        break;
                                    case 1://删除
                                        new CommomDialog(FolderActivity.this, R.style.dialog, "您确定删除此文件夹？", new CommomDialog.OnCloseListener() {
                                            @Override
                                            public void onClick(Dialog dialog, boolean confirm) {
                                                if (confirm) {
                                                    File file = new File(Environment.getExternalStorageDirectory() + "/果乐录音/" + subFile[anchorViewPosition].getName());
                                                    FileUtils.delFile(file, true);
                                                    Toast.makeText(FolderActivity.this, subFile[anchorViewPosition].getName() + "删除完成", Toast.LENGTH_SHORT).show();
                                                    filePath.clear();
                                                    initData();
                                                    dialog.dismiss();
                                                }
                                            }
                                        }).setTitle("提示").show();
                                        break;
                                }
                            }
                        }).show();
                return true;
            }
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        rawX = (int) ev.getRawX();
        rawY = (int) ev.getRawY();
        return super.dispatchTouchEvent(ev);
    }

    // 新增文件夹
    private void getAddFolderDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(FolderActivity.this);
        builder.setTitle("请输入新文件夹");
        //    通过LayoutInflater来加载一个xml的布局文件作为一个View对象
        View view = LayoutInflater.from(FolderActivity.this).inflate(R.layout.item_dialog_add_file, null);
        //    设置我们自己定义的布局文件作为弹出框的Content
        builder.setView(view);
        final EditText editName = view.findViewById(R.id.username);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String edit_add = editName.getText().toString().trim();
                if (TextUtils.isEmpty(edit_add)) {
                    Toast.makeText(FolderActivity.this, "请填写文件夹", Toast.LENGTH_SHORT).show();
                    return;
                }
                for (int i = 0; i < subFile.length; i++) {
                    if (subFile[i].isDirectory()) {
                        if (subFile[i].getName().equals(edit_add)) {
                            Log.e("新文件夹冲突", "新文件夹冲突");
                            Toast.makeText(FolderActivity.this, "新文件夹冲突", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }
                }
                //创建文件夹
                FileUtils.createFileDir(FolderActivity.this, edit_add);
                filePath.clear();
                initData();
                Toast.makeText(FolderActivity.this, "创建成功", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.show();
    }

    /**
     * 遍历文件
     *
     * @param fileAbsolutePath Environment.getExternalStorageDirectory() + "/果乐录音/" 文件夹路径
     * @return
     */
    public Vector<String> getFileName(String fileAbsolutePath) {
        Vector<String> vecFile = new Vector<>();
        File file = new File(fileAbsolutePath);
        subFile = file.listFiles();

        for (int i = 0; i < subFile.length; i++) {
            FolderBean bean = new FolderBean();
            // 判断是否为文件夹
            if (subFile[i].isDirectory()) {
                String filename = subFile[i].getName();
                bean.setFolder_name(subFile[i].getName());
                filePath.add(bean);
                Log.e("文件名", "文件名 ： " + filename);
            }
        }
        return vecFile;
    }

    /**
     * 重命名
     *
     * @param path 原文件名字
     */
    private void showRename(final String path, final int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(FolderActivity.this);
        View view_Rename = LayoutInflater.from(FolderActivity.this).inflate(R.layout.dialog_rename, null);
        TextView cancel = view_Rename.findViewById(R.id.tv_rename_cancel);
        TextView sure = view_Rename.findViewById(R.id.tv_rename_ok);
        final EditText editText = view_Rename.findViewById(R.id.edit_text);
        final Dialog dialog = builder.create();
        dialog.show();
        dialog.getWindow().setContentView(view_Rename);
        //使ediText可以唤起软键盘
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(FolderActivity.this, "cancel", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
        });
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                edit = editText.getText().toString();
                //防止文件重命名冲突
                for (int i = 0; i < subFile.length; i++) {
                    if (subFile[position].isDirectory()) {
                        if (subFile[position].getName().equals(edit)) {
                            Log.e("有重命名文件", "有重命名文件");
                            Toast.makeText(FolderActivity.this, "重命名冲突请再填写", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }
                }
                //重命名文件\文件夹
                FileUtils.rename(Environment.getExternalStorageDirectory() + "/果乐录音" + "/" + path, Environment.getExternalStorageDirectory() + "/果乐录音" + "/" + edit);
                filePath.clear();
                initData();
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        filePath.clear();
        initData();
    }
}
